package com.macasa.panel.entity.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKeyColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import org.hibernate.annotations.ForeignKey;

import com.google.common.base.Objects;
import com.macasa.panel.common.utils.CastHelpers;
import com.macasa.panel.entity.api.IApacheService;
import com.macasa.panel.entity.api.IApacheServiceVhost;
import com.macasa.panel.entity.api.IDomain;

@Entity
@Table(name = "apache_service")
@Getter
@Setter
@ToString(callSuper = true)
public class ApacheService extends Service implements IApacheService {

	/**
	 * The Constant serialVersionUID
	 */
	@Version
	private static final long			serialVersionUID	= -1687451150323635910L;

	@ElementCollection(fetch = FetchType.EAGER)
	@JoinTable(name = "apache_service_ports", joinColumns = @JoinColumn(name = "apache_service_id"))
	@MapKeyColumn(name = "port")
	@Column(name = "ssl", nullable = false)
	@ForeignKey(name = "fk_apache_service_ports_01")
	private Map<Integer, Boolean>		portAvailable;

	@OneToMany(mappedBy = "apacheService", cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = com.macasa.panel.entity.impl.ApacheServiceVhost.class)
	@ForeignKey(name = "fk_apache_service_vhost_01")
	private List<IApacheServiceVhost>	vhosts;

	@OneToMany(mappedBy = "apacheService", cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = com.macasa.panel.entity.impl.Domain.class)
	@ForeignKey(name = "fk_domain_01")
	private List<IDomain>				domains;

	@Override
	public boolean equals(final Object obj) {

		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof ApacheService)) {
			return false;
		}

		final ApacheService other = CastHelpers.cast(obj, ApacheService.class);

		return super.equals(obj) && Objects.equal(this.portAvailable, other.portAvailable) && Objects.equal(this.vhosts, other.vhosts)
				&& Objects.equal(this.domains, other.domains);
	}

	@Override
	public int hashCode() {
		return super.hashCode() + Objects.hashCode(this.portAvailable, this.vhosts, this.domains);
	}
}
